from tkinter import *
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import re
from tkinter import filedialog


class sendmailtool():
    
    def __init__(self):
        pass

    #附件路径功能
    def filepath(self):
        self.path = filedialog.askopenfilenames()
        self.var1.set(self.path)

    def windowssix(self,root):
        w = Toplevel(root)
        w.title('邮件发送工具,')
        w.geometry('950x300')
        w.geometry('+600+400')

        #标签框
        l1 = Label(w,text='邮件客户端工具\n目前只支持QQ邮箱登录',font='12')
        l1.grid(row=1,column=0,padx=5,pady=5)

        l2 = Label(w,text='发件人邮箱',font='12',bg='red')
        l2.grid(row=2,column=0,padx=5,pady=5)

        l22 = Label(w,text='发件人密码',font='12',bg='red')
        l22.grid(row=2,column=2,padx=5,pady=5)

        l23 = Label(w,text='收件人邮箱',font='12',bg='red')
        l23.grid(row=2,column=4,padx=5,pady=5)

        l3 = Label(w,text='邮件主题',font='12',bg='red')
        l3.grid(row=3,column=0,padx=5,pady=5)

        l32 = Label(w,text='邮件内容',font='12',bg='red')
        l32.grid(row=3,column=2,padx=5,pady=5)

        l33 = Label(w,text='附件路径',font='12',bg='red')
        l33.grid(row=3,column=4,padx=5,pady=5)

        #输入框
        self.e2 = Entry(w)
        self.e2.grid(row=2,column=1,padx=5,pady=5)

        self.e22 = Entry(w)
        self.e22.grid(row=2,column=3,padx=5,pady=5)

        self.e23 = Entry(w)
        self.e23.grid(row=2,column=5,padx=5,pady=5)

        self.e3 = Entry(w)
        self.e3.grid(row=3,column=1,padx=5,pady=5)

        self.e32 = Entry(w)
        self.e32.grid(row=3,column=3,padx=5,pady=5)

        self.var1=StringVar()
        self.e33 = Entry(w,textvariable=self.var1)
        self.e33.grid(row=3,column=5,padx=5,pady=5)

        #按键
        b1 = Button(w,text='发送',font='12',bg='red',command=six.getresult)
        b1.grid(row=4,column=0,padx=5,pady=5)

        b2 = Button(w,text='选择附件',font='12',bg='yellow',command=six.filepath)
        b2.grid(row=3,column=6,padx=5,pady=5)

        w.mainloop()

    def getresult(self):
        sendusername = self.e2.get()
        senduserpasswd = self.e22.get()
        connectname = self.e23.get()

        mailtitle = self.e3.get()
        mailcontent = self.e32.get()
        mailpath = self.e33.get()
        filenames = re.split(r'/',mailpath)[-1]

        msg = MIMEMultipart()
        msg['subject']=mailtitle
        msg['From']=sendusername
        msg['To']=connectname
 
        msg.attach(MIMEText(mailtitle,'plain','utf-8'))
        att1 = MIMEText(open('%s'%mailpath,'rb').read(),'base64','utf-8')
        att1["Content-Disposition"] = "attachment; filename = %s"%filenames
        msg.attach(att1)

        s = smtplib.SMTP('mail.139.com',25)
        s.set_debuglevel(1)
        s.login(sendusername,senduserpasswd)
        s.sendmail(sendusername,connectname,msg.as_string())

#类实例化
six = sendmailtool()

#单独执行此文件时，将#号去掉即可
#six.windowssix()